package org.longIt.springdata.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.longIt.springdata.domain.Clazz;
import org.longIt.springdata.domain.Student;
import org.longIt.springdata.repository.ClazzRepository;
import org.longIt.springdata.repository.StudentRepository;
import org.longIt.springdata.service.StudentService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class StudentServiceImpl implements StudentService {

	@Resource
	private StudentRepository studentRepository;
	
	@Resource
	private ClazzRepository clazzRepository;
	

	

	@Override
	public List<Student> findStuDynamic(Student student) {
		
		List<Student> students = studentRepository.findAll(new Specification<Student>() {
			/**
			 *  Predicate：断言
				Root：代表 Table 
				CriteriaQuery：面向对象查询
				CriteriaBuilder：面向对象构建
			 * */
			@Override
			public Predicate toPredicate(Root<Student> root, 
					CriteriaQuery<?> query, 
					CriteriaBuilder criteriaBuilder) {
				
				// 集合，装载动态查询条件（多个）
				List<Predicate> predicates = new ArrayList<>();
				
				// 如果student对象不为空，说明有动态查询条件
				if(student != null) {
					// 如果name不等于null，构建一个name like的where条件 
					if(student.getName()!= null && !student.getName().equals("")) {
						// criteriaBuilder.like(列, 匹配的值)
						predicates.add(criteriaBuilder.like(root.get("name"), "%"+student.getName()+"%"));
					}
					// 如果sex不等于null，构建一个sex like的where条件 
					if(student.getSex()!= null && !student.getSex().equals("")) {
						// criteriaBuilder.like(列, 匹配的值)
						predicates.add(criteriaBuilder.like(root.get("sex"), "%"+student.getSex()+"%"));
					}
					// 如果clazz.name不等于null，构建一个  = 的where条件
					if(student.getClazz()!=null && !student.getClazz().getName().equals("")) {
						root.join("clazz",JoinType.INNER);
						predicates.add(criteriaBuilder.equal(root.get("clazz").get("name"),student.getClazz().getName()));
					}
					// 因为CriteriaQuery的where方法的参数是数组，所以转成数组
					Predicate[] ps = predicates.toArray(new Predicate[predicates.size()]);
					// 组装where条件
					query.where(ps);
				}
				
				// 根据条件查询
				return query.getRestriction();
			}
		});
		
		return students;
	}




}
